package net.qiqbframework.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import net.qiqbframework.eventhandling.gateway.EventGateway;
import net.qiqbframework.messaging.MetaData;
import net.qiqbframework.serialization.SerializationException;
import net.qiqbframework.serialization.Serializer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

@Slf4j
public class RabbitEventReceiver {

    private final EventGateway eventGateway;
    private final Serializer eventSerializer;


    public RabbitEventReceiver(EventGateway eventGateway, Serializer eventSerializer) {
        this.eventGateway = eventGateway;
        this.eventSerializer = eventSerializer;
    }

    @RabbitListener(queues = RabbitBindingConfig.QUEUE_NAME + "${project.name}")
    public void receiveMessage(RabbitEventMessage message) {


        try {
            final MetaData metaData = eventSerializer.deserialize(message.getMetaData());
            final RabbitSerializedObject payloadSerializedObject = message.getPayload();
            Class.forName(payloadSerializedObject.getType().getName());
            final Object payload = eventSerializer.deserialize(payloadSerializedObject);
            //
            eventGateway.publish(payload);
        } catch (ClassNotFoundException e) {
            log.info("消息负载类未找到，无需监听");
        } catch (SerializationException e) {
            // 无需重试，由人工或者发送发重试
            log.error("消息序列异常：", e);
        }

    }
}
